package pw.hais.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pw.hais.config.Config;
import pw.hais.uitl.HttpParam;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 基本控制器
 * route=1 http://localhost:8080/?a=Action&m=method&parm=json
 * route=2 http://localhost:8080/Action/method?parm=json
 * route=3 http://localhost:8080/Action/method/值/值/值/值      -值存在 values
 * @author Hello_海生
 * @date 2014年7月28日
 */
@WebServlet(name = "BaseController", urlPatterns = { "/*" })
public class BaseController extends HttpServlet {
	private static final long serialVersionUID = 1L;
    protected static HttpServletRequest request;
    protected static HttpServletResponse response;
    
    private static String ACTION_NAME="a";	//类名
    private static String METHOD_NAME="m";	//方法名
    
    protected String action;			//控制器
    protected String method;			//方法
    private PrintWriter out = null;
    
    /**
     * 用于返回Json 的 Map
     */
	protected static Map<String, Object> result = new HashMap<String, Object>();	//结果
	
	private List<String> values;
    
    
	
	
    /**
     * 控制跳转
     */
    private void controller(){
    	//获取请求地址 的 类型
    	switch (Config.URLROUTE) {
		case 1:	//普通模式
			action = getString(ACTION_NAME);
	    	method = getString(METHOD_NAME);
			break;
		case 2:	//伪静态模式
			String[] temp = request.getPathInfo().split("/");
			if(temp.length >= 3){
				action = temp[1];
		    	method = temp[2];
			}else{
				action = "";
		    	method = "";
			}
			break;
		case 3: //不懂叫什么
			String[] tmp = request.getPathInfo().split("/");
			if(tmp.length >= 3){
				action = tmp[1];
		    	method = tmp[2];
		    	values = new ArrayList<String>();
		    	for (int i = 3; i < tmp.length; i++) {
		    		values.add(tmp[i]);
				}
			}else{
				action = "";
		    	method = "";
			}
			break;
		}
    	//判断 请求的 操作 是否存在，并调用方法
    	if(!"".equals(action)){
    		try {
    			Class<?> clazz = Class.forName(Config.CONTROLLER_PATH+"."+action+"Controller");
    			Object o =  clazz.newInstance();	//实例化一个类
    			o.getClass().getMethod(method,null).invoke(o, null);	//调用请求
    			String json = JSON.toJSON(result).toString();
    			out.print(json);
			} catch (Exception e) {
				result = setResult(HttpParam.ERROR, "系统出错，请求连接不存在。", "");
				String json = JSON.toJSON(result).toString();
    			out.print(json);

				if(Config.DEBUG){
					System.out.println("--请求不存在。");
					e.printStackTrace();
				}
			}
    		
    	}
    }

    
    /**
	 * 设置返回值
	 * @param code
	 * @param msg
	 * @param data
	 * @return
	 */
	protected Map<String, Object> setResult(String code,String msg,Object data) {
		String c = code==null?"":code;
		String m = msg==null?"":msg;
		Object d = data==null?"":data;
		result.put(HttpParam.CODE, c);
		result.put(HttpParam.MSG, m);
		result.put(HttpParam.DATA, d);
		return result;
	}
	

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    	result = new HashMap<String,Object>();
		//设置输出的编码
    	response.setContentType("application/json;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");

		//赋值
		this.out =  response.getWriter();
		BaseController.request=request;
		BaseController.response = response;
		controller();	//调用方法
    }
    
    public BaseController() {
        super();
    } 
    
    /**
     * 获取路由三方式的 返回结果
     * @return
     */
    public List<String> getValues(){
    	if(Config.URLROUTE==3){
    		if(values!=null)return values;
    	}else{
    		System.out.println("--您未开启 模式三 路由器，无法使用此方法！");
    	}
    	return new ArrayList<String>();
    }
    
    /**
	 * 获取 字符串 类型 参数
	 * @param str
	 * @return
	 */
	public String getString(String str){
		String value = request.getParameter(str);
		if(value==null)value="";
		return value;
	}
	
	/**
	 * 获取 整数 类型 参数
	 * @param str
	 * @return
	 */
	public int getInt(String str){
		int value = 0;
		try {
			value = Integer.parseInt(request.getParameter(str));
		} catch (Exception e) {
			value=0;
		}
		return value;
	}
	
	/**
	 * 获取 长整 类型 参数
	 * @param str
	 * @return
	 */
	public long getlong(String str){
		long value = 0;
		try {
			value = Long.valueOf(request.getParameter(str));
		} catch (Exception e) {
			value=0;
		}
		return value;
	}
	
	/**
	 * 获取 浮点型  类型 参数
	 * @param str 
	 * @return
	 */
	public float getFloat(String str){
		float value = 0;
		try {
			value = Float.valueOf(request.getParameter(str));
		} catch (Exception e) {
			value=0;
		}
		return value;
	}
  
}
